package com.chenfan.magic.core.executer;


import com.chenfan.magic.utils.FastJsonKit;
import com.chenfan.magic.utils.StringKit;

import java.util.Map;

/**
 * EOF 函数
 *
 * @author 周夕
 * @date 2020-02-27 11:16
 */
public class EOFExecuter {

    public static final String EOF = "EOF";

    public static final String EOF_RIGHT_BRACKETS = "EOF(";

    /**
     * 解释型自动中止函数
     * 支持三种形式:
     * 1. EOF
     * 2. EOF("请求失败! ...")
     * 3. EOF({code: 269, msg: "hello"})
     *
     * @param eofMap
     * @param EOF
     * @param prefixKey
     * @return
     */
    public static boolean run(Map<String, Object> eofMap, String EOF, String prefixKey) {
        String msg = "";
        EOF = EOF.trim();
        if (StringKit.isNotBlank(EOF) && EOF.startsWith(EOFExecuter.EOF)) {
            msg = prefixKey + " 主动中止了本次请求";
            if (EOF.contains(EOF_RIGHT_BRACKETS)) {
                msg = EOF.replace(EOF_RIGHT_BRACKETS, "");
                msg = msg.substring(0, msg.length() - 1);
                //接收一个json数组
                try {
                    eofMap = FastJsonKit.jsonstring2Map(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                eofMap.put("msg", msg);
                eofMap.put("code", 269);
            }
            return false;
        }
        return true;
    }
}
